package com.data.mall.utils;

import com.data.mall.config.ClickHouseConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

@Component
@Slf4j
public class CKUtils {

    @Autowired
    ClickHouseConfig clickHouseConfig;


    /**
     * 数据插入
     */
    public boolean insert(String sql) throws SQLException {
        Connection connection = clickHouseConfig.getConn();
        Statement statement = connection.createStatement();
        return statement.execute(sql);
    }

    /**
     * 查询Bean
     */
    public <T> T queryBean(String sql, Class<T> tClass) {
        return executeQuery(sql, tClass);
    }

    private <T> T executeQuery(String sql, Class<T> tClass) {
        log.info("执行sql：" + sql);
        Connection connection = clickHouseConfig.getConn();
        try {
            Statement statement = connection.createStatement();
            ResultSet results = statement.executeQuery(sql);
            if (results.next()){
                return toObject(results, tClass);
            }else {
                return null;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private <T> T toObject(ResultSet resultSet , Class<T> clazz) {
        T t = null;
        try {
            t = clazz.newInstance();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                String setMethodStr = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
                Method setMethod = clazz.getDeclaredMethod(setMethodStr, field.getType());
                setMethod.invoke(t, resultSet.getObject(humpToLine(field.getName())));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return t;
    }

    // 驼峰转下划线
    private String humpToLine(String str) {
        return str.replaceAll("[A-Z]", "_$0").toLowerCase();
    }

}
